package com.czmh.etc.common.core.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

/**
 * 
 * @描述：
 * @author： Seven.
 * @创建日期：Jun 10, 2019 9:20:03 PM.
 * @版本：1.0.0
 */
public class Base64ImageUtil {
    public static final Logger logger = LoggerFactory.getLogger(Base64ImageUtil.class);

	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 * 
	 * @param imgStr       base64字符串
	 * @param imgFile      目标文件
	 * @return
	 */
	public static File generateImage(String imgStr, File imgFile) {
		if (imgStr == null){
			return null;
		}
		// 按字节编码
		byte[] encodeImage = Base64.decodeBase64(imgStr);
		// 生成编码后的jpg图片
		FileImageOutputStream fos1 = null;
		try {
			fos1 = new FileImageOutputStream(imgFile);
			fos1.write(encodeImage);
			fos1.flush();
			return imgFile;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			return imgFile;
		} finally {
			try {
				if (fos1 != null){
					fos1.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
	}

	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * 
	 * @param imgFilePath      图片路径
	 * @return
	 */
	public static String getImageStr(String imgFilePath) {
		byte[] data = null;
		// 读取图片字节数组
		InputStream in = null;
		try {
			in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (in != null){
					in.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
		// 对字节数组Base64编码
		return Base64.encodeBase64String(data);
	}

	public static String getFileName(String ext) {
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date cday = new Date();
		String fileName = sdf.format(cday);
		int randomNum = (int) (Math.random() * 9000 + 1000);
		fileName += randomNum;

		if (StringUtils.isNotEmpty(fileName)) {
			if (ext.startsWith(".")) {
				ext = ext.substring(1);
			}
			fileName += "." + ext;
		}
		return fileName;
	}

	/**
	 * 服务器图片转换base64 path：服务器图片路径  返回 base64编码（String 类型）
	 * @param path
	 * @return
	 */
	public static String imgToBase64(String path){
		byte[] data = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		try{
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			in = connection.getInputStream();
			out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len = 0;
			while((len =in.read(b)) != -1){
				out.write(b,0,len);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			try{
				if(in != null ){
					in.close();
				}
			}catch (IOException e){
				e.getStackTrace();
			}
		}
		System.out.println("转换后的图片大小："+out.toByteArray().length/1024);
		BASE64Encoder base = new BASE64Encoder();
		return base.encode(out.toByteArray());
	}

	public static byte[] readFileToByteArray(String filePath) throws Exception {
		try (InputStream in = new FileInputStream(filePath)) {
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			return bytes;
		}
	}

	public static String hashWithSHA1(String data) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		byte[] digest = md.digest(data.getBytes());
		StringBuilder sb = new StringBuilder();
		for (byte b : digest) {
			sb.append(String.format("%02x", b & 0xff));
		}
		return sb.toString();
	}
}
